package com.xiaozhen.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaozhen.common.core.constant.Constants;
import com.xiaozhen.common.core.utils.StringUtils;
import com.xiaozhen.system.dao.SysDictDataDao;
import com.xiaozhen.system.dao.SysDictTypeDao;
import com.xiaozhen.common.core.domain.system.SysDictData;
import com.xiaozhen.common.core.domain.system.SysDictType;
import com.xiaozhen.system.service.SysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/8/19 15:11
 * @description:
 */
@Service
public class SysDictTypeServiceImpl implements SysDictTypeService {

    @Autowired
    private SysDictTypeDao sysDictTypeDao;
    @Autowired
    private SysDictDataDao sysDictDataDao;

    @Override
    public Page<SysDictType> selectDictTypeList(Page<SysDictType> page, SysDictType dictType) {
        QueryWrapper<SysDictType> queryWrapper = new QueryWrapper<>();
        Page<SysDictType> sysDictTypePage = sysDictTypeDao.selectPage(page, queryWrapper);
        return sysDictTypePage;
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        QueryWrapper<SysDictData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_type", dictType);
        queryWrapper.eq("status", Constants.NORMAL_STATUS);
        List<SysDictData> dictDatas = sysDictDataDao.selectList(queryWrapper);
        if (StringUtils.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        return null;
    }

    @Override
    public Integer insertDictType(SysDictType dictType) {
        return sysDictTypeDao.insert(dictType);
    }

    @Override
    public Boolean checkDictTypeUnique(SysDictType dictType) {
        QueryWrapper<SysDictType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dict_type", dictType.getDictType());
        List<SysDictType> sysDictTypes = sysDictTypeDao.selectList(queryWrapper);
        if (sysDictTypes.size() == 0) {
            return true;
        } else if (dictType.getDictId() != null && dictType.getDictId().equals(sysDictTypes.get(0).getDictId())) {
            return true;
        }
        return false;
    }

    @Override
    public Integer updateDictType(SysDictType dictType) {
        return sysDictTypeDao.updateById(dictType);
    }

    @Override
    public Integer deleteDictTypeByIds(Long dictId) {
        int count = sysDictTypeDao.deleteById(dictId);
        return count;
    }
}
